<template>
    <div class="app-container">
        <div class="filter-container">
                <el-input v-model="listQuery.orgCode" placeholder="机构代码" style="width: 80px;" class="filter-item" @keyup.enter.native="handleFilter" />
                <el-input v-model="listQuery.orgName" placeholder="机构名称" style="width: 80px;" class="filter-item" @keyup.enter.native="handleFilter" />
            <el-button v-waves class="filter-item" type="primary" icon="el-icon-search" @click="handleFilter">
                {{ $t('table.search') }}
            </el-button>
            <el-button class="filter-item" style="margin-left: 10px;" type="primary" icon="el-icon-edit" @click="handleCreate('root')">
                添加根节点
            </el-button>
            <el-button class="filter-item" style="margin-left: 10px;" type="primary" icon="el-icon-edit" @click="handleCreate('sub')">
                添加子节点
            </el-button>
        </div>

        <el-table
                :key="tableKey"
                v-loading="listLoading"
                :data="list"
                border
                fit
                row-key="id"
                :tree-props="{children: 'children', hasChildren: 'hasChildren'}"
                @current-change="handleCurrentChange"
                highlight-current-row
                style="width: 100%;margin-top:10px"
                @sort-change="sortChange"
        >
                <el-table-column label="id" prop="id" sortable="true" align="center" width="80" >
                    <template slot-scope="{row}">
                        <span>{{ row.id }}</span>
                    </template>
                </el-table-column>
                <el-table-column label="机构代码" prop="orgCode" sortable="true" align="center" width="80" >
                    <template slot-scope="{row}">
                        <span>{{ row.orgCode }}</span>
                    </template>
                </el-table-column>
                <el-table-column label="机构名称" prop="orgName" sortable="true" align="center" width="80" >
                    <template slot-scope="{row}">
                        <span>{{ row.orgName }}</span>
                    </template>
                </el-table-column>
                <el-table-column label="联系电话" prop="linkPhone" sortable="true" align="center" width="80" >
                    <template slot-scope="{row}">
                        <span>{{ row.linkPhone }}</span>
                    </template>
                </el-table-column>
                <el-table-column label="邮箱" prop="linkEmail" sortable="true" align="center" width="80" >
                    <template slot-scope="{row}">
                        <span>{{ row.linkEmail }}</span>
                    </template>
                </el-table-column>
                <el-table-column label="机构级别" prop="type" sortable="true" align="center" width="80" >
                    <template slot-scope="{row}">
                        <span>{{ row.type | dictValueFilter('ORG_LEVEL')}}</span>
                    </template>
                </el-table-column>
                <el-table-column label="联系人姓名" prop="contactor" sortable="true" align="center" width="80" >
                    <template slot-scope="{row}">
                        <span>{{ row.contactor }}</span>
                    </template>
                </el-table-column>
                <el-table-column label="状态" prop="status" sortable="true" align="center" width="80" >
                    <template slot-scope="{row}">
                        <span>{{ row.status | dictValueFilter('BASE_STATUS')}}</span>
                    </template>
                </el-table-column>
                <el-table-column label="备注" prop="remarks" sortable="true" align="center" width="80" >
                    <template slot-scope="{row}">
                        <span>{{ row.remarks }}</span>
                    </template>
                </el-table-column>
            <el-table-column label="操作" align="center" width="300px" class-name="small-padding fixed-width">
                <template slot-scope="{row,$index}">
                    <el-button type="primary" size="mini" @click="handleUpdate(row)">
                        {{ $t('table.edit') }}
                    </el-button>
                    <el-button  size="mini" type="danger" @click="handleDelete(row,$index)">
                        {{ $t('table.delete') }}
                    </el-button>
                </template>
            </el-table-column>
        </el-table>


        <el-dialog :title="textMap[dialogStatus]" :visible.sync="dialogFormVisible">
            <el-form ref="dataForm" :rules="rules" :model="temp"  label-width="120px" style="width: 300px; margin-left:50px;">
                    <el-form-item label="机构代码" prop="orgCode">
                        <el-input v-model="temp.orgCode" />
                    </el-form-item>
                    <el-form-item label="机构名称" prop="orgName">
                        <el-input v-model="temp.orgName" />
                    </el-form-item>
                    <el-form-item label="联系电话" prop="linkPhone">
                        <el-input v-model="temp.linkPhone" />
                    </el-form-item>
                    <el-form-item label="邮箱" prop="linkEmail">
                        <el-input v-model="temp.linkEmail" />
                    </el-form-item>
                    <el-form-item label="机构级别" prop="type">
                        <base-select :dictType="'ORG_LEVEL'" v-model="temp.type" class="filter-item" placeholder="Please select">
                        </base-select>
                    </el-form-item>
                    <el-form-item label="父机构id" prop="parentOrgId">
                        <el-input v-model="temp.parentOrgId" disabled="true"/>
                    </el-form-item>
                    <el-form-item label="联系人姓名" prop="contactor">
                        <el-input v-model="temp.contactor" />
                    </el-form-item>
                    <el-form-item label="状态" prop="status">
                        <base-select :dictType="'BASE_STATUS'" v-model="temp.status" class="filter-item" placeholder="Please select">
                        </base-select>
                    </el-form-item>
                    <el-form-item label="备注" prop="remarks">
                        <el-input v-model="temp.remarks" />
                    </el-form-item>
            </el-form>
            <div slot="footer" class="dialog-footer">
                <el-button @click="dialogFormVisible = false">
                    {{ $t('table.cancel') }}
                </el-button>
                <el-button type="primary" @click="dialogStatus==='create'?createData():updateData()">
                    {{ $t('table.confirm') }}
                </el-button>
            </div>
        </el-dialog>

    </div>
</template>

<script>
    import { page , create, update, del,selectOne ,all,iteratorSearchOrgCode,iteratorSearchOrgName} from '@/api/rbac/Org'
    import waves from '@/directive/waves' // waves directive
    import { parseTime } from '@/utils'
    import Pagination from '@/components/Pagination' // secondary package based on el-pagination
    import BaseSelect from '@/components/Dict'
    import { MessageBox } from 'element-ui'


    export default {
        name: 'org',
        components: { Pagination,BaseSelect },
        directives: { waves },
        filters: {
        },
        data() {
            return {
                tableKey: 0,
                list: null,
                total: 0,
                listLoading: true,
                listQuery: {
                    page: 1,
                    limit: 20,
                    sort: 'id desc',
                            id : '',
                            orgCode : '',
                            orgName : '',
                            linkPhone : '',
                            linkEmail : '',
                            type : '',
                            parentOrgId : '',
                            contactor : '',
                            status : '',
                            remarks : '',
                            createTime : '',
                            createUserid : '',
                            updateTime : '',
                            updateUserid : ''
                },
                temp: {
                    id : '',
                    orgCode : '',
                    orgName : '',
                    linkPhone : '',
                    linkEmail : '',
                    type : '',
                    parentOrgId : '',
                    contactor : '',
                    status : '',
                    remarks : '',
                    createTime : '',
                    createUserid : '',
                    updateTime : '',
                    updateUserid : ''
                },
                dialogFormVisible: false,
                dialogStatus: '',
                textMap: {
                    update: '编辑',
                    create: '新增'
                },
                rules: {
                },
                currentRow: null,
                downloadLoading: false
            }
        },
        created() {
            this.getList()
        },
        methods: {
            getList() {
                this.listLoading = true
                all().then(response => {
                    this.list = response.data
                    this.listLoading = false
            })
            },
            handleFilter() {
                this.getQueryList()
            },
            getQueryList(){
                if(this.listQuery.orgCode == '' && this.listQuery.orgName==''){
                    this.getList()
                }else{
                    if(this.list == null || this.list.length == 0){
                        this.getList()
                    }
                    var array = []
                    this.list.forEach(element => {
                        if(this.listQuery.orgCode !=''){
                            const filterResult = iteratorSearchOrgCode(element,this.listQuery.orgCode)
                            if(filterResult){
                                array.push(element)
                            }
                        }
                       if(this.listQuery.orgName !=''){
                           const filterResult = iteratorSearchOrgName(element,this.listQuery.orgName)
                            if(filterResult){
                                array.push(element)
                            }
                       }
                    });
                    this.list = array
                }
            },
            handleModifyStatus(row, status) {
                this.$message({
                    message: '操作成功',
                    type: 'success'
                })
                row.status = status
            },
            sortChange(data) {
                const { prop, order } = data
                //   if (prop === 'id') {
                this.sortBy(prop,order)
                //   }
            },
            sortBy(prop,order) {
                if (order === 'ascending') {
                    this.listQuery.sort = prop + ' asc'
                } else {
                    this.listQuery.sort = prop + ' desc'
                }
                this.handleFilter()
            },
            resetTemp() {
                this.temp = {
                            id : '',
                            orgCode : '',
                            orgName : '',
                            linkPhone : '',
                            linkEmail : '',
                            type : '',
                            parentOrgId : '',
                            contactor : '',
                            status : '',
                            remarks : '',
                            createTime : '',
                            createUserid : '',
                            updateTime : '',
                            updateUserid : ''
                }
            },
            handleCreate(type) {
                this.resetTemp()
                if(type =='root'){
                    this.temp.parentOrgId = 0;
                }else if(type =='sub'){
                    if(this.currentRow==null){
                        this.$notify({
                                title: '校验失败',
                                message: '请选择父节点',
                                type: 'error',
                                duration: 2000
                            })
                            return
                    }
                    this.temp.parentOrgId = this.currentRow.id;
                }
                this.dialogStatus = 'create'
                this.dialogFormVisible = true
                this.$nextTick(() => {
                    this.$refs['dataForm'].clearValidate()
                })
            },
            createData() {
                this.$refs['dataForm'].validate((valid) => {
                    if (valid) {
                        create(this.temp).then(() => {
                            this.list.unshift(this.temp)
                            this.dialogFormVisible = false
                            this.$notify({
                                title: '成功',
                                message: '创建成功',
                                type: 'success',
                                duration: 2000
                            })
                            this.getList()
                        })
                    }
                })
            },
            handleUpdate(row) {
                selectOne(row.id).then(response =>{
                    this.temp = response.data
                    this.dialogStatus = 'update'
                    this.dialogFormVisible = true
                    this.$nextTick(() => {
                        this.$refs['dataForm'].clearValidate()
                    })
            }).catch(error =>{
                    this.$notify({
                        title: '失败',
                        message: error,
                        type: 'error',
                        duration: 2000
                    })
                })

            },
            updateData() {
                this.$refs['dataForm'].validate((valid) => {
                    if (valid) {
                        const tempData = Object.assign({}, this.temp)
                        update(tempData).then(() => {
                        this.dialogFormVisible = false
                        this.$notify({
                            title: '成功',
                            message: '更新成功',
                            type: 'success',
                            duration: 2000
                        })
                        this.getList()
                    })
                    }
                })
            },
            handleDelete(row, index) {
                MessageBox.confirm('是否确认删除', {
                    confirmButtonText: '确认',
                    cancelButtonText: '取消',
                    type: 'warning'
                }).then(()=>{
                    del(row.id).then(response =>{
                        this.$notify({
                            title: '成功',
                            message: '删除成功',
                            type: 'success',
                            duration: 2000
                        })
                        this.getList()
                    }).catch(error =>{
                        this.$notify({
                            title: '删除失败',
                            message: error,
                            type: 'error',
                            duration: 2000
                        })
                    })
                })
            },
            handleCurrentChange(val) {
                this.currentRow = val;
            }
        }
    }
</script>
